package com.xunan.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import com.xunan.demo.pojo.CommonResult;
import com.xunan.demo.pojo.WechatPaymentData;
import com.xunan.demo.service.WechatPaymentService;
import com.xunan.demo.service.WechatUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;


@Slf4j
@CrossOrigin
@RestController
public class WechatPaymentController {

    @Resource
    private WechatPaymentService wechatPaymentService;

    @Resource
    private WechatUserService wechatUserService;

    /**
     * 微信支付回调
     *
     * @param body 微信提供的支付回调数据
     */
    @PostMapping("/wechat-payment/paymentNotify")
    public void paymentNotify(
            @RequestHeader Map<String, String> headers,
            @RequestBody String body) {

        //验证签名
        boolean signResult = wechatPaymentService.verifyHttpSign(headers, body);
        if (!signResult) {
            log.warn("签名验证失败");
            return;
        } else {
            log.info("签名验证成功");
        }

        //数据处理
        JSONObject notifyObj = JSON.parseObject(body);
        wechatPaymentService.paymentNotify(notifyObj);
    }

    /**
     * 查询支付记录
     *
     * @param transactionId  微信支付订单号（与商户订单号二选一）
     * @param outTradeNumber 商户订单号（与微信支付订单号二选一）
     * @return 支付数据
     */
    @GetMapping("/wechat-payment/getTransaction")
    public CommonResult<JSONObject> getTransaction(String transactionId, String outTradeNumber) {

        if (transactionId == null && outTradeNumber == null) {
            return new CommonResult<>(false,"参数不足，无法获取信息",null);
        }

        return wechatPaymentService.getTransaction(transactionId, outTradeNumber);
    }

    /**
     * 获取支付信息
     *
     * @param loginCode   登录Code（与userOpenId二选一）
     * @param userOpenId  用户的微信OpenId （与loginCode二选一）
     * @param description 商品描述
     * @param totalAmount 总价
     * @return 支付数据
     */
    @PostMapping("/wechat-payment/getPayData")
    public CommonResult<WechatPaymentData> getPayData(String loginCode,
                                        String userOpenId,
                                        @RequestParam String description,
                                        @RequestParam Integer totalAmount) {
        //验证描述长度
        int descriptionLength = description.length();
        if (descriptionLength < 1 || descriptionLength > 127) {
            return new CommonResult<>(false,"description字段长度限制为[1,126]",null);
        }

        //如果是loginCode的话就需要转化为OpenId
        if (loginCode != null) {
            userOpenId = wechatUserService.getUserWechatOpenId(loginCode);
        }

        //如果为空则不继续执行了
        if (userOpenId == null) {
            return new CommonResult<>(false,"无法获取用户标识符",null);
        } else {
            log.info("已获取用户OpenId：" + userOpenId);
        }

        return wechatPaymentService.getPayData(userOpenId, description, totalAmount);
    }

}
